package com.example.mydataapplication;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class External extends Fragment {
    public External()
    {
        super(R.layout.external);
    }
    private final String FILE_NAME="Enternal.txt";
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view,savedInstanceState);
        getView().findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(
                            new FileOutputStream(
                                    new File(getActivity().getExternalFilesDir(null),FILE_NAME))));
                    bw.write("外部HelloWorld");
                    bw.close();
                    Toast.makeText(getActivity(),"外部写入成功",Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedReader br=new BufferedReader(new InputStreamReader(
                            new FileInputStream(
                                    new File(getActivity().getExternalFilesDir(null),FILE_NAME))));
                    Toast.makeText(getActivity(),br.readLine(),Toast.LENGTH_SHORT).show();
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
